package cn.glow.readingcloud.book.service.impl;
import  cn.glow.readingcloud.common.pojo.Book;

import cn.glow.readingcloud.book.dao.BookMapper;
import cn.glow.readingcloud.book.service.BookService;
import cn.glow.readingcloud.common.constant.CategoryConstant;
import cn.glow.readingcloud.common.enums.BookSerialStatusEnum;
import cn.glow.readingcloud.common.result.Result;
import cn.glow.readingcloud.common.result.ResultUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import pojo.BookView;

/**
 * @Author Glow
 * @Date 2023-04-14 15:06:03
 * @Description
 * @Version 1.0
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

@Autowired
private BookMapper bookMapper;
@Autowired
private RedisTemplate redisTemplate;

    @Override
    public Result<Book> getBookById(String bookId) {

            Book book = (Book) redisTemplate.opsForHash().get("Book",bookId);
            if(book == null)
            {
                LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Book::getBookId,bookId);
               book = bookMapper.selectOne(queryWrapper);
               try{
                   redisTemplate.opsForHash().put("Book",bookId,book);
               }catch (Exception e)
               {
                   return ResultUtil.error().buildMessage("服务器异常请重试！");
               }

            }
                return ResultUtil.success(book).buildMessage("获取book成功！");
    }

    @Override
    public Result<BookView> getBookDetails(String bookId) {
        Book book = this.getBookById(bookId).getData();
        if (book == null) {
            return ResultUtil.notFound().buildMessage("找不到"+bookId+"这本书哦！");
        }
        BookView bookView = new BookView();
        BeanUtils.copyProperties(book,bookView);
        //设置转换分类代码和图书状态代码
        bookView.setCategoryName(CategoryConstant.categorys.get(book.getDicCategory()));
        bookView.setSerialStatusName(BookSerialStatusEnum.values()[book.getDicSerialStatus()-1].getName());

        return ResultUtil.success(bookView);
    }
}
